package com.yanyeori.framework.jira.utils;

import com.yanyeori.framework.jira.jiraclient.Issue;
import com.yanyeori.framework.jira.jiraclient.JiraClient;
import com.yanyeori.framework.jira.jiraclient.JiraException;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * jira util
 *
 * @author chenkuan
 * @since 2023/3/16
 */
public class JiraUtil {

    private final JiraClient jiraClient;

    public JiraUtil(JiraClient jiraClient) {
        this.jiraClient = jiraClient;
    }

    /**
     * 查询issue
     *
     * @param issueKey issueKey
     * @return Issue
     */
    public Issue getIssue(String issueKey) throws JiraException {
        return jiraClient.getIssue(issueKey);
    }

    /**
     * 批量查询issue
     *
     * @param issueKeys      issueKey列表
     * @param includedFields 查询字段
     * @return Map<String, Issue>
     */
    public Map<String, Issue> listIssue(List<String> issueKeys, String... includedFields) throws JiraException {
        if (CollectionUtils.isEmpty(issueKeys)) {
            return new HashMap<>(0);
        }
        Set<String> issueKeySet = issueKeys.stream().map(String::toLowerCase).collect(Collectors.toSet());
        String jql = String.format("issueKey in (%s)", StringUtils.join(issueKeySet, ","));
        String includedField = ArrayUtils.isNotEmpty(includedFields) ? StringUtils.join(includedFields, ",") : null;
        Issue.SearchResult result = jiraClient.searchIssues(jql, includedField, issueKeySet.size());
        List<Issue> issues = result.issues;
        if (CollectionUtils.isEmpty(issues)) {
            return new HashMap<>(0);
        }
        return issues.stream().collect(Collectors.toMap(Issue::getKey, x -> x));
    }

    /**
     * 批量查询issue状态
     *
     * @param issueKeys issueKey列表
     * @return Map<String, String>
     */
    public Map<String, String> listIssueStatus(List<String> issueKeys) throws JiraException {
        Map<String, Issue> issueMap = listIssue(issueKeys, "status");
        if (MapUtils.isEmpty(issueMap)) {
            return new HashMap<>(0);
        }
        return issueMap.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, x -> x.getValue().getStatus().getName()));
    }
}
